package com.ruibo.modules.common.controller;

import com.ruibo.annotation.AnonymousAccess;
import com.ruibo.config.FileProperties;
import com.ruibo.modules.common.service.upload.proxy.FileUploadProxy;
import com.ruibo.utils.FileUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @program: ruibo-parent
 * @description: 通用图片，视频上传接口
 * @author: Sun Feng
 * @create: 2020-06-30 15:31
 **/
@Slf4j
@RestController
@RequestMapping("/common/file")
@AllArgsConstructor
public class CommonController {

    private final FileUploadProxy fileUploadProxy;

    private final FileProperties fileProperties;


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @AnonymousAccess
    @GetMapping("download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtil.isValidFilename(fileName)) {
                throw new Exception(com.ruibo.utils.StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = fileName.substring(fileName.indexOf("_") + 1);
            // 上传文件基础路径
            String filePath = fileProperties.getPath().getPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtil.setFileDownloadHeader(request, realFileName));
            FileUtil.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtil.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }


    /**
     * 这个文件上传为上传到fastDFS和OOS的
     *
     * @param file
     * @return
     * @throws IOException
     */
    @AnonymousAccess
    @PostMapping(value = "/upload")
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        String upload = fileUploadProxy.upload(file, StringUtils.getFilenameExtension(file.getOriginalFilename()));
        return new ResponseEntity<>(upload, HttpStatus.OK);
    }

    /**
     * 实现文件上传到本地服务器
     *
     * @param file
     * @return
     * @throws IOException
     */
    @AnonymousAccess
    @PostMapping(value = "/localUpload")
    public ResponseEntity localUpload(@RequestParam("file") MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        // 上传文件基础路径
        String filePath = fileProperties.getPath().getPath();

        // 上传并返回新文件名称
        String fileName = FileUtil.upload(filePath, file);
        String attachmentType = FileUtil.getExtensionName(fileName);
        HashMap<String, Object> map = new HashMap<>(4);
        // 目前只是存的文件名称
        map.put("fileName", fileName);
        map.put("attachmentType", attachmentType);
        map.put("code", 200);
        map.put("msg", "操作成功");
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
}
